'use client';

import React, { useState } from 'react';
import Button from '@/components/ui/Button';
import { 
  Plus,
  Search,
  Upload,
  Download,
  Eye,
  Edit,
  Image,
  FileText,
  Database,
  Clock,
  CheckCircle,
  Filter,
  Activity,
  HardDrive
} from 'lucide-react';

interface Dataset {
  id: string;
  name: string;
  type: 'image' | 'sequence' | 'text' | 'mixed';
  category: 'worker_recognition' | 'defect_detection' | 'environment_hazard' | 'knowledge_base';
  status: 'processing' | 'ready' | 'error';
  size: number;
  samples: number;
  createdAt: string;
  lastUpdated: string;
  description: string;
  format: string;
  annotations: boolean;
  quality: 'high' | 'medium' | 'low';
  usage: 'training' | 'validation' | 'test' | 'inference';
}

export default function DatasetsPage() {
  const [datasets] = useState<Dataset[]>([
    {
      id: '1',
      name: '作业场景数据集v3.2',
      type: 'image',
      category: 'worker_recognition',
      status: 'ready',
      size: 2.8,
      samples: 15420,
      createdAt: '2024-11-15',
      lastUpdated: '2024-12-01',
      description: '包含多种电力作业场景的高质量图像数据，涵盖登杆作业、地面作业、设备检修等场景',
      format: 'JPEG/PNG',
      annotations: true,
      quality: 'high',
      usage: 'training'
    },
    {
      id: '2',
      name: '设备缺陷图像数据集',
      type: 'image',
      category: 'defect_detection',
      status: 'ready',
      size: 4.2,
      samples: 23650,
      createdAt: '2024-11-20',
      lastUpdated: '2024-12-02',
      description: '电力设备缺陷检测专用数据集，包含绝缘子破损、导线断裂、设备腐蚀等缺陷类型',
      format: 'JPEG',
      annotations: true,
      quality: 'high',
      usage: 'training'
    },
    {
      id: '3',
      name: '环境隐患检测数据集',
      type: 'image',
      category: 'environment_hazard',
      status: 'processing',
      size: 1.9,
      samples: 8750,
      createdAt: '2024-11-25',
      lastUpdated: '2024-12-03',
      description: '电力设施周边环境隐患检测数据，包含树木倒伏、异物悬挂、施工干扰等场景',
      format: 'JPEG/PNG',
      annotations: false,
      quality: 'medium',
      usage: 'training'
    },
    {
      id: '4',
      name: '时序缺陷数据集',
      type: 'sequence',
      category: 'defect_detection',
      status: 'ready',
      size: 0.8,
      samples: 5420,
      createdAt: '2024-10-15',
      lastUpdated: '2024-11-10',
      description: '基于时间序列的设备状态监测数据，包含温度、振动、电流等传感器数据',
      format: 'CSV/JSON',
      annotations: true,
      quality: 'high',
      usage: 'validation'
    },
    {
      id: '5',
      name: '电力知识库文本数据',
      type: 'text',
      category: 'knowledge_base',
      status: 'error',
      size: 0.3,
      samples: 12800,
      createdAt: '2024-09-20',
      lastUpdated: '2024-10-05',
      description: '电力行业标准、规范、技术文档等文本数据，用于大模型知识增强',
      format: 'TXT/PDF',
      annotations: false,
      quality: 'medium',
      usage: 'training'
    }
  ]);

  const [searchTerm, setSearchTerm] = useState('');
  const [typeFilter, setTypeFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');
  const [categoryFilter, setCategoryFilter] = useState('all');

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'processing':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800 border border-yellow-200">
          <span className="w-1.5 h-1.5 bg-yellow-600 rounded-full mr-1.5"></span>
          处理中
        </span>;
      case 'ready':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 border border-green-200">
          <span className="w-1.5 h-1.5 bg-green-600 rounded-full mr-1.5"></span>
          就绪
        </span>;
      case 'error':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 border border-red-200">
          <span className="w-1.5 h-1.5 bg-red-600 rounded-full mr-1.5"></span>
          错误
        </span>;
      default:
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 border border-gray-200">
          {status}
        </span>;
    }
  };

  const getTypeBadge = (type: string) => {
    switch (type) {
      case 'image':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 border border-blue-200">
          <Image className="w-3 h-3 mr-1" />
          图像
        </span>;
      case 'sequence':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 border border-green-200">
          <Activity className="w-3 h-3 mr-1" />
          序列
        </span>;
      case 'text':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-orange-100 text-orange-800 border border-orange-200">
          <FileText className="w-3 h-3 mr-1" />
          文本
        </span>;
      case 'mixed':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-800 border border-purple-200">
          <Database className="w-3 h-3 mr-1" />
          混合
        </span>;
      default:
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 border border-gray-200">
          {type}
        </span>;
    }
  };

  const getCategoryName = (category: string) => {
    switch (category) {
      case 'worker_recognition':
        return '人员识别';
      case 'defect_detection':
        return '缺陷检测';
      case 'environment_hazard':
        return '环境隐患';
      case 'knowledge_base':
        return '知识库';
      default:
        return category;
    }
  };

  const getQualityBadge = (quality: string) => {
    switch (quality) {
      case 'high':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 border border-green-200">
          高质量
        </span>;
      case 'medium':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800 border border-yellow-200">
          中等质量
        </span>;
      case 'low':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 border border-red-200">
          低质量
        </span>;
      default:
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 border border-gray-200">
          {quality}
        </span>;
    }
  };

  const getTypeIcon = (type: string) => {
    switch (type) {
      case 'image':
        return <Image className="h-4 w-4" aria-label="Image type" />;
      case 'sequence':
        return <Clock className="h-4 w-4" aria-label="Sequence type" />;
      case 'text':
        return <FileText className="h-4 w-4" aria-label="Text type" />;
      default:
        return <Database className="h-4 w-4" aria-label="Database type" />;
    }
  };

  const filteredDatasets = datasets.filter(dataset => {
    return (
      (searchTerm === '' || dataset.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
       dataset.description.toLowerCase().includes(searchTerm.toLowerCase())) &&
      (typeFilter === 'all' || dataset.type === typeFilter) &&
      (statusFilter === 'all' || dataset.status === statusFilter) &&
      (categoryFilter === 'all' || dataset.category === categoryFilter)
    );
  });

  // 统计数据
  const stats = {
    total: datasets.length,
    ready: datasets.filter(d => d.status === 'ready').length,
    processing: datasets.filter(d => d.status === 'processing').length,
    error: datasets.filter(d => d.status === 'error').length,
    totalSize: datasets.reduce((sum, d) => sum + d.size, 0),
    totalSamples: datasets.reduce((sum, d) => sum + d.samples, 0)
  };

  return (
    <div className="space-y-4">
      {/* 紧凑的标题栏 */}
      <div className="flex items-center justify-between rounded-lg px-4 py-3">
        <div>
          <h1 className="text-xl font-bold text-gray-900">数据集管理</h1>
          <p className="text-sm text-gray-600 mt-0.5">电力场景数据集管理与配置</p>
        </div>
        <div className="flex gap-2">
          <Button variant="secondary" size="sm">
            <Upload className="h-4 w-4 mr-1.5" />
            上传
          </Button>
          <Button variant="primary" size="sm">
            <Plus className="h-4 w-4 mr-1.5" />
            新建数据集
          </Button>
        </div>
      </div>

      {/* 紧凑的统计卡片 */}
      <div className="grid grid-cols-2 lg:grid-cols-6 gap-3">
        <div className="bg-gradient-to-br from-blue-50 to-blue-100 border border-blue-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-blue-700 uppercase tracking-wide">总数据集</div>
              <div className="text-2xl font-bold text-blue-900 mt-1">{stats.total}</div>
            </div>
            <Database className="h-6 w-6 text-blue-600" />
          </div>
        </div>
        
        <div className="bg-gradient-to-br from-green-50 to-green-100 border border-green-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-green-700 uppercase tracking-wide">就绪</div>
              <div className="text-2xl font-bold text-green-900 mt-1">{stats.ready}</div>
            </div>
            <CheckCircle className="h-6 w-6 text-green-600" />
          </div>
        </div>
        
        <div className="bg-gradient-to-br from-yellow-50 to-yellow-100 border border-yellow-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-yellow-700 uppercase tracking-wide">处理中</div>
              <div className="text-2xl font-bold text-yellow-900 mt-1">{stats.processing}</div>
            </div>
            <Activity className="h-6 w-6 text-yellow-600" />
          </div>
        </div>
        
        <div className="bg-gradient-to-br from-red-50 to-red-100 border border-red-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-red-700 uppercase tracking-wide">错误</div>
              <div className="text-2xl font-bold text-red-900 mt-1">{stats.error}</div>
            </div>
            <Database className="h-6 w-6 text-red-600" />
          </div>
        </div>
        
        <div className="bg-gradient-to-br from-purple-50 to-purple-100 border border-purple-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-purple-700 uppercase tracking-wide">总容量</div>
              <div className="text-2xl font-bold text-purple-900 mt-1">{stats.totalSize.toFixed(1)}GB</div>
            </div>
            <HardDrive className="h-6 w-6 text-purple-600" />
          </div>
        </div>
        
        <div className="bg-gradient-to-br from-orange-50 to-orange-100 border border-orange-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-orange-700 uppercase tracking-wide">总样本</div>
              <div className="text-2xl font-bold text-orange-900 mt-1">{(stats.totalSamples / 1000).toFixed(0)}K</div>
            </div>
            <Image className="h-6 w-6 text-orange-600" />
          </div>
        </div>
      </div>

      {/* 搜索和筛选栏 */}
      <div className="bg-white border border-gray-200 rounded-lg p-4 shadow-sm">
        <div className="flex flex-col sm:flex-row gap-3">
          <div className="flex-1">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
              <input
                type="text"
                placeholder="搜索数据集名称或描述..."
                className="w-full pl-10 pr-4 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
          </div>
          
          <div className="flex gap-2">
            <select
              className="px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              value={typeFilter}
              onChange={(e) => setTypeFilter(e.target.value)}
            >
              <option value="all">所有类型</option>
              <option value="image">图像</option>
              <option value="sequence">序列</option>
              <option value="text">文本</option>
              <option value="mixed">混合</option>
            </select>
            
            <select
              className="px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
            >
              <option value="all">所有状态</option>
              <option value="ready">就绪</option>
              <option value="processing">处理中</option>
              <option value="error">错误</option>
            </select>
            
            <select
              className="px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              value={categoryFilter}
              onChange={(e) => setCategoryFilter(e.target.value)}
            >
              <option value="all">所有分类</option>
              <option value="worker_recognition">人员识别</option>
              <option value="defect_detection">缺陷检测</option>
              <option value="environment_hazard">环境隐患</option>
              <option value="knowledge_base">知识库</option>
            </select>
          </div>
        </div>
      </div>

      {/* 数据集列表 */}
      <div className="bg-white border border-gray-200 rounded-lg shadow-sm">
        <div className="p-4 border-b border-gray-200">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold text-gray-900">数据集列表</h2>
            <span className="text-sm text-gray-600">共 {filteredDatasets.length} 个数据集</span>
          </div>
        </div>
        
        <div className="divide-y divide-gray-200">
          {filteredDatasets.map((dataset) => (
            <div key={dataset.id} className="p-4 hover:bg-gray-50 transition-colors">
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <div className="flex items-center gap-3 mb-2">
                    {getTypeIcon(dataset.type)}
                    <h3 className="text-lg font-medium text-gray-900">{dataset.name}</h3>
                    {getStatusBadge(dataset.status)}
                    {getTypeBadge(dataset.type)}
                  </div>
                  
                  <p className="text-sm text-gray-600 mb-3">{dataset.description}</p>
                  
                  <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4 text-sm">
                    <div>
                      <span className="text-gray-500">分类:</span>
                      <span className="ml-1 font-medium text-gray-900">{getCategoryName(dataset.category)}</span>
                    </div>
                    <div>
                      <span className="text-gray-500">大小:</span>
                      <span className="ml-1 font-medium text-gray-900">{dataset.size}GB</span>
                    </div>
                    <div>
                      <span className="text-gray-500">样本:</span>
                      <span className="ml-1 font-medium text-gray-900">{dataset.samples.toLocaleString()}</span>
                    </div>
                    <div>
                      <span className="text-gray-500">格式:</span>
                      <span className="ml-1 font-medium text-gray-900">{dataset.format}</span>
                    </div>
                    <div>
                      <span className="text-gray-500">标注:</span>
                      <span className={`ml-1 font-medium ${dataset.annotations ? 'text-green-600' : 'text-red-600'}`}>
                        {dataset.annotations ? '已标注' : '未标注'}
                      </span>
                    </div>
                    <div>
                      <span className="text-gray-500">质量:</span>
                      <span className="ml-1">{getQualityBadge(dataset.quality)}</span>
                    </div>
                  </div>
                  
                  <div className="flex items-center gap-4 mt-3 text-xs text-gray-500">
                    <span>创建: {dataset.createdAt}</span>
                    <span>更新: {dataset.lastUpdated}</span>
                    <span>用途: {dataset.usage === 'training' ? '训练' : dataset.usage === 'validation' ? '验证' : dataset.usage === 'test' ? '测试' : '推理'}</span>
                  </div>
                </div>
                
                <div className="flex items-center gap-2 ml-4">
                  <button className="p-2 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded-md transition-colors">
                    <Eye className="h-4 w-4" />
                  </button>
                  <button className="p-2 text-gray-400 hover:text-green-600 hover:bg-green-50 rounded-md transition-colors">
                    <Download className="h-4 w-4" />
                  </button>
                  <button className="p-2 text-gray-400 hover:text-orange-600 hover:bg-orange-50 rounded-md transition-colors">
                    <Edit className="h-4 w-4" />
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 底部统计汇总 */}
      <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
          <div className="text-center">
            <div className="text-2xl font-bold text-gray-900">{filteredDatasets.length}</div>
            <div className="text-gray-600">筛选结果</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-blue-600">{filteredDatasets.reduce((sum, d) => sum + d.size, 0).toFixed(1)}GB</div>
            <div className="text-gray-600">总容量</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-green-600">{(filteredDatasets.reduce((sum, d) => sum + d.samples, 0) / 1000).toFixed(0)}K</div>
            <div className="text-gray-600">总样本</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-purple-600">{filteredDatasets.filter(d => d.annotations).length}</div>
            <div className="text-gray-600">已标注</div>
          </div>
        </div>
      </div>
    </div>
  );
} 